<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/30
 * Time: 下午1:51
 */

namespace App\Http\Controllers\Api\Shop;



use App\Http\Controllers\Controller;

use App\Libs\Pay\WechatPay;
use App\Modules\Order\Services\OrderService;
use App\Modules\Shop\Services\GiftSendService;
use App\Modules\User\Services\UserService;
use Illuminate\Http\Request;


class AliPayController extends Controller
{
    /**
     * 支付宝支付回调
     *
     * @param Request $request
     */
   public function alipay_callback(Request $request) {
       $req = $request->all();
       /*\Log::info('alipay_res');
       \Log::info($req);*/
       \Log::info(file_get_contents('php://input'));
       $order =OrderService::findByTradeNo($req['out_trade_no']);

        if (!$order || $order->status == OrderService::ORDER_STATUS_PAID) { // 如果订单不存在 或者 订单已经支付过了
           echo 'success'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        if(array_key_exists('trade_status',$req) && 'TRADE_SUCCESS'==$req['trade_status']) {
            $order->pay_end_at = date('Y-m-d H:i:s',time()); // 更新支付时间为当前时间
            $order->status = OrderService::ORDER_STATUS_PAID;
            $order->transaction_id = $req['trade_no'];
            $order->notify_data = json_encode($req);
            $order->save();
            #
            $order_products = $order->order_products;
            foreach ($order_products as $key=>$order_product) {
                $order_product->status = OrderService::ORDER_STATUS_PAID;
                $order_product->save();
                if($order_product->is_vip_product ==1) { //处理购买VIP套餐
                    if($order_product->is_gift==1){
                        $gift_send = GiftSendService::getByOrderProductId($order_product->id);
                        $gift_send->status = 1;
                        $gift_send->save();
                    }else {
                        $vip_month = $order_product->product->vip_month;
                        $user_info = UserService::getById($order->uid);
                        $user_info->vip =1;
                        $user_info->vip_start_at = date('Y-m-d H:i:s');
                        $user_info->vip_end_at = date('Y-m-d H:i:s',strtotime('+'.$vip_month.' month'));
                        $user_info->save();
                    }
                }
            }
            echo 'success'; //告诉支付宝后台，处理完成
        }else{
            \Log::error('paid error:'.json_encode($req));
        }
   }
}